package com.chs.recoginition.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.chs.recoginition.aip.ImageRecognitionClient;
import com.chs.recoginition.aip.Ovooa;
import com.chs.recoginition.core.utils.FileAndBaseUtils;
import com.chs.recoginition.core.utils.HttpClientUtil;
import com.chs.recoginition.core.utils.UploadUtil;
import com.chs.recoginition.core.utils.baidu.Base64Util;
import com.chs.recoginition.core.utils.baidu.FileUtil;
import com.chs.recoginition.pojo.IdentificationContent;
import com.chs.recoginition.service.ImageRecognitionService;
import com.chs.recoginition.vo.respVo.ImageRecognitionRespVo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author CHS
 * @Date 2023/2/8 23:36
 * @Version 1.0
 **/
@Service
public class ImageRecognitionServiceImpl implements ImageRecognitionService {

    Logger logger = LoggerFactory.getLogger(ImageRecognitionServiceImpl.class);
    @Autowired
    private ImageRecognitionClient client;
    @Autowired
    private Ovooa ovooa;
    @Value("${localhost}")
    private String localhost;

    @Value("${baidubce.grant_type}")
    private String grantType;
    @Value("${baidubce.client_id}")
    private String clientId;
    @Value("${baidubce.client_secret}")
    private String clientSecret;


    @Override
    public String getToken() {

        JSONObject jsonObject = client.getToken(grantType, clientId, clientSecret);
        if (jsonObject.containsKey("access_token")) {
            return jsonObject.getString("access_token");
        }
        return null;
    }

    @Override
    public ImageRecognitionRespVo getAdvancedGeneral(String image) throws IOException {
        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        req.add("baike_num", 3);
        JSONObject advancedGeneral = client.getAdvancedGeneral(req);
        JSONArray arrays = advancedGeneral.getJSONArray("result");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        for (int i = 0; i < arrays.toArray().length; i++) {
            IdentificationContent respVo = new IdentificationContent();
            String name = arrays.getJSONObject(i).getString("keyword");
            respVo.setId(IdWorker.get32UUID());
            respVo.setName(name);
            BigDecimal score = arrays.getJSONObject(i).getBigDecimal("score").multiply(
                    BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
            respVo.setScore(score);
            if (arrays.getJSONObject(i).containsKey("baike_info") && !arrays.getJSONObject(i)
                    .getJSONObject("baike_info").isEmpty()) {
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("image_url")) {
                    respVo.setImagePath(arrays.getJSONObject(i).getJSONObject("baike_info")
                            .getString("image_url"));
                }
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("description")) {
                    respVo.setMessage(arrays.getJSONObject(i).getJSONObject("baike_info")
                            .getString("description"));
                }
            }

            if (StringUtils.isBlank(respVo.getImagePath()) || StringUtils.isBlank(respVo.getMessage())) {
                Map<String, String> message = findMessage(name);
                respVo.setImagePath(message.get("path"));
                respVo.setMessage(message.get("content"));
            }

            childRespVos.add(respVo);
        }


        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });

        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非通用物品与场景");
            respVo.setName("非通用物品与场景");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public ImageRecognitionRespVo getAnimal(String image) throws IOException {
        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        req.add("baike_num", 3);
        JSONObject advancedGeneral = client.getAnimal(req);
        System.out.println(advancedGeneral);
        JSONArray arrays = advancedGeneral.getJSONArray("result");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        for (int i = 0; i < arrays.toArray().length; i++) {
            IdentificationContent respVo = new IdentificationContent();
            String name = arrays.getJSONObject(i).getString("name");
            respVo.setId(IdWorker.get32UUID());
            respVo.setName(name);
            BigDecimal score = arrays.getJSONObject(i).getBigDecimal("score").multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
            respVo.setScore(score);
            if (arrays.getJSONObject(i).containsKey("baike_info") && !arrays.getJSONObject(i).getJSONObject("baike_info").isEmpty()) {
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("image_url")) {
                    respVo.setImagePath(arrays.getJSONObject(i).getJSONObject("baike_info").getString("image_url"));
                }
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("description")) {
                    respVo.setMessage(arrays.getJSONObject(i).getJSONObject("baike_info").getString("description"));
                }
            }

            if (StringUtils.isBlank(respVo.getImagePath()) || StringUtils.isBlank(respVo.getMessage())) {
                Map<String, String> message = findMessage(name);
                respVo.setImagePath(message.get("path"));
                respVo.setMessage(message.get("content"));
            }

            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });
        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非动物");
            respVo.setName("非动物");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public ImageRecognitionRespVo getPlant(String image) throws IOException {
        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        req.add("baike_num", 3);
        JSONObject advancedGeneral = client.getPlant(req);
        JSONArray arrays = advancedGeneral.getJSONArray("result");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        for (int i = 0; i < arrays.toArray().length; i++) {
            IdentificationContent respVo = new IdentificationContent();
            String name = arrays.getJSONObject(i).getString("name");
            respVo.setId(IdWorker.get32UUID());
            respVo.setName(name);
            BigDecimal score = arrays.getJSONObject(i).getBigDecimal("score").multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
            respVo.setScore(score);
            if (arrays.getJSONObject(i).containsKey("baike_info") && !arrays.getJSONObject(i).getJSONObject("baike_info").isEmpty()) {
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("image_url")) {
                    respVo.setImagePath(arrays.getJSONObject(i).getJSONObject("baike_info").getString("image_url"));
                }
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("description")) {
                    respVo.setMessage(arrays.getJSONObject(i).getJSONObject("baike_info").getString("description"));
                }
            }

            if (StringUtils.isBlank(respVo.getImagePath()) || StringUtils.isBlank(respVo.getMessage())) {
                Map<String, String> message = findMessage(name);
                respVo.setImagePath(message.get("path"));
                respVo.setMessage(message.get("content"));
            }

            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });
        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非植物");
            respVo.setName("非植物");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public ImageRecognitionRespVo getLogo(String image) throws IOException {
        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        JSONObject advancedGeneral = client.getLogo(req);
        JSONArray arrays = advancedGeneral.getJSONArray("result");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        for (int i = 0; i < arrays.toArray().length; i++) {
            IdentificationContent respVo = new IdentificationContent();
            String name = arrays.getJSONObject(i).getString("name");
            respVo.setId(IdWorker.get32UUID());
            respVo.setName(name);
            BigDecimal score = arrays.getJSONObject(i).getBigDecimal("probability").multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
            respVo.setScore(score);
            if (StringUtils.isBlank(respVo.getImagePath()) || StringUtils.isBlank(respVo.getMessage())) {
                Map<String, String> message = findMessage(name);
                respVo.setImagePath(message.get("path"));
                respVo.setMessage(message.get("content"));
            }

            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });
        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非Logo");
            respVo.setName("非Logo");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public ImageRecognitionRespVo getIngredient(String image) throws IOException {

        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        JSONObject advancedGeneral = client.getIngredient(req);
        JSONArray arrays = advancedGeneral.getJSONArray("result");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        for (int i = 0; i < arrays.toArray().length; i++) {
            IdentificationContent respVo = new IdentificationContent();
            String name = arrays.getJSONObject(i).getString("name");
            respVo.setId(IdWorker.get32UUID());
            respVo.setName(name);
            BigDecimal score = arrays.getJSONObject(i).getBigDecimal("score").multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
            respVo.setScore(score);
            if (StringUtils.isBlank(respVo.getImagePath()) || StringUtils.isBlank(respVo.getMessage())) {
                Map<String, String> message = findMessage(name);
                respVo.setImagePath(message.get("path"));
                respVo.setMessage(message.get("content"));
            }

            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });
        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非果蔬");
            respVo.setName("非果蔬");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public ImageRecognitionRespVo getDish(String image) throws IOException {
        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        req.add("baike_num", 3);
        JSONObject advancedGeneral = client.getDish(req);
        JSONArray arrays = advancedGeneral.getJSONArray("result");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        for (int i = 0; i < arrays.toArray().length; i++) {
            IdentificationContent respVo = new IdentificationContent();
            String name = arrays.getJSONObject(i).getString("name");
            respVo.setId(IdWorker.get32UUID());
            respVo.setName(name);
            BigDecimal score = arrays.getJSONObject(i).getBigDecimal("probability").multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
            respVo.setScore(score);
            if (arrays.getJSONObject(i).containsKey("baike_info") && !arrays.getJSONObject(i).getJSONObject("baike_info").isEmpty()) {
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("baike_url")) {
                    respVo.setImagePath(arrays.getJSONObject(i).getJSONObject("baike_info").getString("baike_url"));
                }
                if (arrays.getJSONObject(i).getJSONObject("baike_info").containsKey("description")) {
                    respVo.setMessage(arrays.getJSONObject(i).getJSONObject("baike_info").getString("description"));
                }
            }
            if (StringUtils.isBlank(respVo.getImagePath()) || StringUtils.isBlank(respVo.getMessage())) {
                Map<String, String> message = findMessage(name);
                respVo.setImagePath(message.get("path"));
                respVo.setMessage(message.get("content"));
            }

            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });
        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非菜品");
            respVo.setName("非菜品");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;

    }

    @Override
    public ImageRecognitionRespVo getRedWine(String image) throws IOException {

        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        JSONObject advancedGeneral = client.getRedWine(req);
        JSONObject arrays = advancedGeneral.getJSONObject("result");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        String wineNameCn = arrays.getString("wineNameCn");
        if (StringUtils.isBlank(wineNameCn)) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非红酒");
            respVo.setName("非红酒");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        } else {
            String hasdetail = arrays.getString("hasdetail");
            String str = "";
            if (hasdetail.equals(1)) {
                String wineNameEn = arrays.getString("wineNameEn");
                String countryCn = arrays.getString("countryCn");
                String wineryCn = arrays.getString("wineryCn");
                String classifyByColor = arrays.getString("classifyByColor");
                String color = arrays.getString("color");
                String grapeCn = arrays.getString("grapeCn");
                String tasteTemperature = arrays.getString("tasteTemperature");
                String description = arrays.getString("description");
                if (StringUtils.isNotBlank(wineNameEn)) {
                    str += "红酒英文名：" + wineNameEn + ";";
                }
                if (StringUtils.isNotBlank(countryCn)) {
                    str += "国家中文名：" + countryCn + ";";
                }
                if (StringUtils.isNotBlank(wineryCn)) {
                    str += "酒庄中文名：" + wineryCn + ";";
                }
                if (StringUtils.isNotBlank(classifyByColor)) {
                    str += "酒类型：" + classifyByColor + ";";
                }
                if (StringUtils.isNotBlank(color)) {
                    str += "色泽：" + color + ";";
                }
                if (StringUtils.isNotBlank(grapeCn)) {
                    str += "葡萄品种：" + grapeCn + ";";
                }
                if (StringUtils.isNotBlank(tasteTemperature)) {
                    str += "品尝温度：" + tasteTemperature + ";";
                }
                if (StringUtils.isNotBlank(description)) {
                    str += "描述：" + description + ";";
                }
            }
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setName(wineNameCn);
            respVo.setMessage(str);
            if(StringUtils.isBlank(respVo.getMessage())) {
                Map<String, String> message = findMessage(wineNameCn);
                respVo.setImagePath(message.get("path"));
                respVo.setMessage(message.get("content"));
            }
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });

        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public ImageRecognitionRespVo getCurrency(String image) throws IOException {
        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        JSONObject advancedGeneral = client.getCurrency(req);
        JSONObject arrays = advancedGeneral.getJSONObject("result");
        String currencyName = arrays.getString("currencyName");

        List<IdentificationContent> childRespVos = new ArrayList<>();
        if (StringUtils.isBlank(currencyName)) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非货币");
            respVo.setName("非货币");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        } else {
            String str = "";
            String hasdetail = arrays.getString("hasdetail");
            if (hasdetail.equals(1)) {
                String currencyDenomination = arrays.getString("currencyDenomination");
                String year = arrays.getString("year");

                if (StringUtils.isNotBlank(currencyDenomination)) {
                    str += "货币面值：" + currencyDenomination + ";";
                }
                if (StringUtils.isNotBlank(year)) {
                    str += "货币年份：" + year + ";";
                }
                if (StringUtils.isNotBlank(year)) {
                    str += "货币年份：" + year + ";";
                }
            }

            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setName(currencyName);
            Map<String, String> message = findMessage(currencyName);
            respVo.setImagePath(message.get("path"));
            respVo.setMessage(str + "\n" + message.get("content"));

            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });
        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非货币");
            respVo.setName("非货币");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public ImageRecognitionRespVo getLandmark(String image) throws IOException {

        ImageRecognitionRespVo result = new ImageRecognitionRespVo();
        Map<String, String> imageBase64 = getImageBase64(image);
        String parentUrl = imageBase64.get("url");
        String accessToken = getToken();
        MultiValueMap<String, Object> req = new LinkedMultiValueMap<>();
        req.add("access_token", accessToken);
        req.add("image", imageBase64.get("base64"));
        JSONObject advancedGeneral = client.getLandmark(req);
        JSONObject arrays = advancedGeneral.getJSONObject("result");
        String landmark = arrays.getString("landmark");
        List<IdentificationContent> childRespVos = new ArrayList<>();
        if (StringUtils.isBlank(landmark)) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非地标");
            respVo.setName("非地标");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        } else {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setName(landmark);
            Map<String, String> message = findMessage(landmark);
            respVo.setImagePath(message.get("path"));
            respVo.setMessage(message.get("content"));
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        childRespVos.forEach(v -> {
            if (StringUtils.isBlank(v.getMessage())) {
                v.setMessage("未找到相关信息");
            }
            if (StringUtils.isBlank(v.getImagePath())) {
                v.setImagePath(parentUrl);
            }
        });
        if (childRespVos.isEmpty()) {
            IdentificationContent respVo = new IdentificationContent();
            respVo.setId(IdWorker.get32UUID());
            respVo.setImagePath(parentUrl);
            respVo.setMessage("非地标");
            respVo.setName("非地标");
            respVo.setScore(BigDecimal.valueOf(99.00));
            childRespVos.add(respVo);
        }
        result.setChildRespVos(childRespVos);
        result.setImagePath(parentUrl);
        result.setId(IdWorker.get32UUID());
        return result;
    }

    @Override
    public JSONObject getMsg(String msg) {
        return ovooa.getMsg(msg);
    }

    @Override
    public Map<String, String> getImageBase64(String image64) throws IOException {
        Map<String, String> result = new HashMap<>();

        Map<String, Object> stringObjectMap = FileAndBaseUtils.base64ToFile(image64, "images/baidu", "auto");
        MultipartFile multipartFile = FileAndBaseUtils.getMultipartFile((File) stringObjectMap.get("file"));
        String path = stringObjectMap.get("path").toString();
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile != null && !multipartFile.isEmpty()) {
            logger.info("保存的图片路径：[{}]", path);
            // 压缩到小于指定文件大小1m
            double targetSize = 128 * 1024;
            try {
                //从MultipartFile 中获取 byte[]
                logger.info("头像图片压缩前大小：[{}]", bytes.length);
                while (bytes.length > targetSize) {
                    BufferedImage image = FileAndBaseUtils.resizeImage(FileAndBaseUtils.bytesToBufferedImage(bytes), 500, 500);
                    bytes = FileAndBaseUtils.imageToBytes(image);
//                    bytes = resizeImage(bytes,0.5F);
                }
                logger.info("头像图片压缩后大小：[{}]", bytes.length);
                BufferedImage newImage = FileAndBaseUtils.bytesToBufferedImage(bytes);
                //图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存，文件存在会覆盖原文件保存)
                ImageIO.write(newImage, "jpg", new File(UploadUtil.getRootPath() + path));
                byte[] imgData = FileUtil.readFileByBytes(UploadUtil.getRootPath() + path);
                String imgStr = Base64Util.encode(imgData);
                path = UploadUtil.localhost + "/imageRecognition/" + path;
                result.put("base64", imgStr);
                result.put("url", path);
            } catch (IOException e) {
                //抛出异常
                logger.info("转换并保存图片异常:{}", e.getMessage());
            }
        }

        return result;
    }


    public Map<String, String> findMessage(String keyWord) {
        Map<String, String> result = new HashMap<>();
        String url = "https://baike.baidu.com/item/" + keyWord;
        String html = HttpClientUtil.doGet(url);
        Document doc = Jsoup.parse(html);
        String content = doc.select("meta[name=description]").attr("content");
        String path = doc.select("meta[name=image]").attr("content");
        result.put("content", content);
        result.put("path", path);
        return result;
    }

    public static void main(String[] args) {
        for(int i=0;i<20;i++) {
            System.out.println(IdWorker.get32UUID());
        }
    }
}
